package cn.kgc;


import cn.kgc.entity.User;
import cn.kgc.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class App {

    private static SqlSessionFactory factory;

    static {
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory  = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        // List<User> users = selectAll();
        // users.forEach(System.out::println);

        // User user = selectOne(1);
        // System.out.println("user = " + user);

        User user = new User();
        user.setId(9L);
        user.setPassword("666666");

        // Integer integer = addUser(user);
        // Integer integer = updateUser(user);
        Integer integer = deleteUser(9);
        System.out.println("integer = " + integer);

    }

    public static List<User> selectAll(){

        SqlSession sqlSession = factory.openSession(true);
        // 获取动态生成的代理对象    接口实现类
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //org.apache.ibatis.binding.MapperProxy@2f8f5f62
        System.out.println("mapper = " + mapper);
        List<User> users = mapper.selectAll();
         return  users;
    }


    public static User selectOne(Integer id){
        SqlSession sqlSession = factory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectOne(1);
        sqlSession.close();
        return user;
    }

    public static Integer addUser(User user){
        SqlSession sqlSession = factory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Integer integer = mapper.addUser(user);
        sqlSession.close();
        return integer;
    }

    public static Integer updateUser(User user){
        SqlSession sqlSession = factory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Integer integer = mapper.updateUser(user);
        sqlSession.close();
        return integer;
    }

    public static Integer deleteUser(Integer id){
        SqlSession sqlSession = factory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Integer integer = mapper.deleteById(id);
        sqlSession.close();
        return integer;
    }
}
